package com.infinit.easyreader.fragment;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.infinit.easyreader.Biz.OnlineRankTypeBiz;
import com.infinit.easyreader.Biz.RankContentBiz;
import com.infinit.easyreader.Biz.RecommendBiz;
import com.infinit.easyreader.R;
import com.infinit.easyreader.adpter.RankFragmentPagerAdapter;
import com.infinit.easyreader.adpter.RecommendAdapter;
import com.infinit.easyreader.entity.RankContent;
import com.infinit.easyreader.ui.BookContentActivity;
import com.infinit.easyreader.utils.Consts;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

public class CloudFragment extends android.support.v4.app.Fragment implements Consts {


    public static final String RANK_TIME_NAME = "rankName";
    private static final int SWITCH_SPEED = 5000;
    private static final int START_SWITCH = 1001;
    @Bind(R.id.vpIntro)
    ViewPager vpIntro;

    @Bind(R.id.rankName)
    TabLayout rankName;
    @Bind(R.id.vpRank)
    ViewPager vpRank;
    @Bind(R.id.rbLeft)
    RadioButton rbLeft;
    @Bind(R.id.rbMid)
    RadioButton rbMid;
    @Bind(R.id.rbRight)
    RadioButton rbRight;
    private Handler handler;
    private RecommendAdapter rAdapter;
    private boolean isAutoSwitch = true;
    private Thread switchThread;
    private List<View> viewList;
    private List<android.support.v4.app.Fragment> fragments;
    private RankFragmentPagerAdapter rankAdapter;
    private List<RankContent> contents;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cloud, container, false);
        ButterKnife.bind(this, view);
        isAutoSwitch = true;
        handler = new Handler(new Handler.Callback() {
            @SuppressWarnings("unchecked")
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case RankContentBiz.CODE_RANKCONTENT_SUCCESS:
                        contents = (List<RankContent>) msg.obj;
                        //生成轮播的3个View
                        genViewForRecommend(contents);
                        rAdapter.setViews(viewList);
                        rAdapter.notifyDataSetChanged();
                        //开启轮播线程
                        autoSwitch();
                        break;
                    case RankContentBiz.CODE_RANKCONTENT_FAIL:
                        Toast.makeText(getActivity(), "连接网络失败,请稍后再试!", Toast.LENGTH_SHORT).show();
                        break;
                    case OnlineRankTypeBiz.CODE_SUCCESS:
                        Map<String, List<String>> rankMap = (Map<String, List<String>>) msg.obj;
                        List<String> rankTimes = rankMap.get(OnlineRankTypeBiz.KEY_RANKTIME);
                        setAdapter();
                        setListener();
                        new RecommendBiz(getActivity(), handler).getRecommendInfoFromInternet();
                        genRankFragments(rankTimes);
                        rankAdapter.notifyDataSetChanged();
                        rankName.setupWithViewPager(vpRank);
                        //获取Rank信息成功
                        break;
                    case OnlineRankTypeBiz.CODE_ERROR:
                        Toast.makeText(getActivity(), "连接网络失败,请稍后再试!", Toast.LENGTH_SHORT).show();
                        //将preferences中保存的时间数据置为0
                        SharedPreferences preference = getActivity().getSharedPreferences(Consts.PREFERENCE_NAME, Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = preference.edit();
                        editor.putLong(OnlineRankTypeBiz.PREFRENCE_RANK_TIME, 0);
                        editor.apply();
                        break;
                    case START_SWITCH:
                        //开始滚动VpIntro
                        if (isAutoSwitch) {
                            switchPager();
                        }
                        break;
                }
                return true;
            }
        });
        new OnlineRankTypeBiz(getActivity(), handler).getRankInfo();
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    /**
     * 设置监听器
     */
    private void setListener() {

//        lvBooksPtr.setPtrHandler(new PtrDefaultHandler() {
//            @Override
//            public void onRefreshBegin(PtrFrameLayout frame) {
//                Log.d(TAG, "onRefreshBegin: 开始执行更新  ");
//                frame.refreshComplete();
//            }
//
//
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return super.checkCanDoRefresh(frame, content, header);
//
//            }
//        });


        /**
         * 为vpIntro设置监听器
         */


        vpIntro.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //改变radioButton的状态
                switch (position) {
                    case 0:
                        rbLeft.setChecked(true);
                        break;
                    case 1:
                        rbMid.setChecked(true);
                        break;
                    case 2:
                        rbRight.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        /**
         * 为TabLayout设置监听器
         */

        rankName.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                vpRank.setCurrentItem(position);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        /**
         * 为vpIntro设置点击监听器
         */


        rAdapter.setOnItemClickListener(new RecommendAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View view) {
                RankContent content = contents.get(position);
                Intent intent = new Intent(getActivity(), BookContentActivity.class);
                intent.putExtra(RankListFragment.INTENT_CONTENT, content);
                startActivity(intent);
            }
        });

        vpIntro.setOnHoverListener(new View.OnHoverListener() {
            @Override
            public boolean onHover(View v, MotionEvent event) {
                isAutoSwitch = false;
                return false;
            }
        });


    }

    /**
     * 设置适配器
     */


    private void setAdapter() {

        //设置vpIntro的适配器
        genViewForRecommendAdapter();
        rAdapter = new RecommendAdapter(viewList);
        vpIntro.setAdapter(rAdapter);
        //设置vpRank的适配器
        List<String> titles = new ArrayList<>();
        titles.add("日排行");
        titles.add("周排行");
        titles.add("月排行");
        titles.add("总排行");
        genRankFragments(titles);
        rankAdapter = new RankFragmentPagerAdapter(getActivity().getSupportFragmentManager(), fragments, titles);
        vpRank.setAdapter(rankAdapter);

    }

    /**
     * 生成用于轮播展示的3个View
     *
     * @param contents 从网络获取的数据源
     */
    private void genViewForRecommend(List<RankContent> contents) {
        int i = 0;

        for (final RankContent content : contents) {
            View v = viewList.get(i);
            TextView tvBookName = (TextView) v.findViewById(R.id.recommendBookName);
            final ImageView ivBookCover = (ImageView) v.findViewById(R.id.ivRecommend);
            TextView tvAuthor = (TextView) v.findViewById(R.id.tvAuthor);
            //设置数据
            tvBookName.setText(content.getContentName());
            ImageLoader loader = ImageLoader.getInstance();
            loader.displayImage(content.getCoverUrl(), ivBookCover, new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String s, View view) {
                    ivBookCover.setBackgroundColor(Color.GRAY);
                }

                @Override
                public void onLoadingFailed(String s, View view, FailReason failReason) {
                    Log.d(TAG, "onLoadingFailed: " + content.getCoverUrl());

                }

                @Override
                public void onLoadingComplete(String s, View view, Bitmap bitmap) {

                }

                @Override
                public void onLoadingCancelled(String s, View view) {

                }
            });
            tvAuthor.setText(content.getAuthorName());
            i++;
        }
    }

    /**
     * 开启子线程来自动滑动vpIntro
     */

    private void autoSwitch() {


        switchThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (isAutoSwitch) {
                        Thread.sleep(SWITCH_SPEED);
                        Message.obtain(handler, START_SWITCH).sendToTarget();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        switchThread.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isAutoSwitch = false;
        switchThread = null;
    }

    /**
     * 滚动ViewPager
     */


    private void switchPager() {
        int currentPosition = vpIntro.getCurrentItem();
        if (currentPosition == 2) {
            vpIntro.setCurrentItem(0);
        } else {
            vpIntro.setCurrentItem(currentPosition + 1);
        }
    }

    /**
     * 设置vpIntro的适配器
     */


    private void genViewForRecommendAdapter() {
        viewList = new ArrayList<>();
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        @SuppressLint("InflateParams") View v1 = inflater.inflate(R.layout.item_recommend, null, false);
        @SuppressLint("InflateParams") View v2 = inflater.inflate(R.layout.item_recommend, null, false);
        @SuppressLint("InflateParams") View v3 = inflater.inflate(R.layout.item_recommend, null, false);
        viewList.add(v1);
        viewList.add(v2);
        viewList.add(v3);
    }


    /**
     * 生成4个Fragments
     */

    private void genRankFragments(List<String> titles) {
        fragments = new ArrayList<>();

        if (titles != null) {
            for (String title : titles) {
                Bundle bundle = new Bundle();
                bundle.putString(RANK_TIME_NAME, title);
                android.support.v4.app.Fragment fragment = new RankListFragment();
                fragment.setArguments(bundle);
                fragments.add(fragment);
            }


        }


    }


}
